<template>
  <div class="app-container">
    <div class="filter-container">
      <span class="filter-title filter-item">红包状态</span>
      <k-select
        v-model="listQuery.redPacketStatus"
        class="filter-item user-status"
        type="1"
        :select-params="[{label:'未认领',value: 1},{label:'认领中',value: 2},{label:'已认领',value: 3}]"
        @handleSelectEvent="handleFilter"
      />
      <span class="filter-title filter-item">红包时间</span>
      <k-date-picker
        v-model="timeValue"
        type="datetimerange"
        valueFormat="yyyy-MM-dd HH:mm:ss"
        class="filter-item"
        @hqchang="handleFilter"
      />
      <k-input
        v-model.trim="listQuery.key"
        class="filter-item"
        is-search
        placeholder="请输入关键词"
        :search-fun="handleFilter"
        @keyup.enter.native="handleFilter"
      />
    </div>
    <!-- 创建 roll 房 -->
    <k-button v-if="authorityHandle(61)" class="top-btn" value="创建红包" @click.native="creatBloodDialog" />
    <!-- <k-button class="top-btn" value="玩法介绍" @click.native="ruleGuideDialog" /> -->

    <!--表格相关 -->
    <el-table
      :data="bloodTableData"
      fit
      :show-summary="!authorityHandle(63)"
      :summary-method="getSummaries"
      border
      highlight-current-row
      style="width: 100%;border-radius:8px;"
      :header-cell-style="{background:'#F6F5FA',color:'#4E4F62'}"
    >
      <el-table-column width="80px" type="index" label="序号" align="center" />
      <el-table-column prop="envelopeTheme" min-width="100px" label="红包主题" align="center" show-overflow-tooltip />
      <el-table-column porp="envelopeMinAmount" min-width="80px" label="红包金额（F）" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.envelopeMinAmount }} - {{ scope.row.envelopeMaxAmount }}
        </template>
      </el-table-column>
      <el-table-column prop="creatorName" min-width="100px" label="创建人" align="center" show-overflow-tooltip />
      <el-table-column prop="envelopeStatusName" min-width="80px" label="红包状态" align="center" show-overflow-tooltip />
      <el-table-column min-width="150px" label="生效时间" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.startTime }} - {{ scope.row.endTime }}
        </template>
      </el-table-column>
      <el-table-column prop="envelopePassword" min-width="90px" label="红包码" align="center" />
      <el-table-column min-width="90px" label="获奖者用户名" align="center">
        <template slot-scope="scope">
          {{ scope.row.userList.length > 0 ? scope.row.userList[0].mobile + ' ...' : "" }}
        </template>
      </el-table-column>
      <el-table-column min-width="80px" label="开关" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.openStatus"
            active-color="#3b425d"
            inactive-color="#E9EBF2"
            active-text="开"
            inactive-text="关"
            :active-value="1"
            :inactive-value="2"
            :disabled="!authorityHandle(61)"
            @change="updateBloodStatus($event,scope)"
          />
        </template>
      </el-table-column>
      <el-table-column min-width="200px" label="操作" align="center">
        <template slot-scope="scope">
          <div class="op-div">
            <k-button class="table-btn" value="查看/修改" @click.native="updateBloodDialog(scope.row)" />
            <k-button v-if="authorityHandle(61)" class="table-btn" value="删除" :disabled="scope.row.openStatus===1?true:false" @click.native="deleteRedItem(scope.row.id)" />
            <k-button class="table-btn" value="参与名单" @click.native="openuserListDialog(scope.row.id)" />
          </div>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="totalRows > 0"
      :total="totalRows"
      :page.sync="listQuery.pager.pageNo"
      :limit.sync="listQuery.pager.pageSize"
      @pagination="loadData"
    />
    <!-- 玩法介绍 弹窗 -->
    <k-dialog
      :show-hide.sync="ruleGuide.showHide"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="玩法介绍"
      class-name="ruleGuide-dialog"
      :show-foot="false"
      :two-btn="authorityHandle(61)"
      @click="guideSave"
    >
      <div class="dialog-ruleGuide" style="padding:30px">
        <el-form :model="ruleGuideContent" label-width="auto">
          <el-form-item label="内容介绍：" prop="content">
            <quill-editor
              ref="myQuillEditor"
              v-model.trim="ruleGuideContent.content"
              :options="editorOption"
              class="editer"
            />
          </el-form-item>
        </el-form>
      </div>
    </k-dialog>

    <!-- 创建红包 弹窗 -->
    <k-dialog
      :show-hide.sync="creatRollRoom.showHide"
      :modal-append-to-body="false"
      :append-to-body="true"
      :title="textMap[dialogStatus]"
      class-name="creatRollRoom_dialog"
      :show-foot="false"
      :two-btn="authorityHandle(61) && updateButtonState"
      :close-fun="handleCloseDialog"
      @click="saveBloodRed"
    >
      <div class="dialog_creatRollRoom">
        <el-form :model="bloodRedInfo" label-width="auto">
          <el-form-item label="红包主题：">
            <el-input :readonly="!authorityHandle(61)" v-model="bloodRedInfo.envelopeTheme" show-word-limit placeholder="请输入红包主题" />
          </el-form-item>
          <el-form-item label="红包简介：">
            <el-input
             :readonly="!authorityHandle(61)"
              v-model="bloodRedInfo.envelopeIntroduce"
              type="textarea"
              :rows="3"
              show-word-limit
              placeholder="请输入红包简介"
            />
          </el-form-item>

          <el-form-item label="领取方式：">
            <div class="chargeform">
              <el-select :disabled="!authorityHandle(61)" v-model="bloodRedInfo.receiveType" placeholder="请选择领取方式" class="red_money">
                <el-option label="进群领取" :value="1" />
                <el-option label="红包码领取" :value="2" />
              </el-select>
            </div>
          </el-form-item>
          <el-form-item label="红包金额（F）区间：">
            <el-input :readonly="!authorityHandle(61)" v-model="bloodRedInfo.envelopeMinAmount" onkeyup="value=value.replace(/[^0-9.]/g,'')" class="red_money" />
            <i style="margin: 0 3px;"> — </i>
            <el-input :readonly="!authorityHandle(61)" v-model="bloodRedInfo.envelopeMaxAmount" onkeyup="value=value.replace(/[^0-9.]/g,'')" class="red_money" />
          </el-form-item>
          <el-form-item label="有效时间：" style="width:300px">
            <el-date-picker
             :disabled="!authorityHandle(61)"
              v-model="timeCotinue"
              type="datetimerange"
              value-format="yyyy-MM-dd HH:mm:ss"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="datetimerange"
            />
          </el-form-item>
          <el-form-item label="获奖者用户名：">
            <search-select
              ref="KsearchSelect"
              :readonlyState="!authorityHandle(61)"
              :result-list="winnerUserList"
              @requestReslutList="requestReslutList"
              @selectChange="selectChange"
              @visibleChange="visibleChange"
            />
          </el-form-item>
        </el-form>
      </div>
    </k-dialog>
    <!-- 参与人名单 -->
    <k-dialog
      :show-hide.sync="userListDialog.showHide"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="参与人名单"
      class-name="creatRollRoom_dialog"
      :show-foot="false"
      :two-btn="false"
    >
      <div>
        <!--表格相关 -->
        <el-table
          :data="userPlayList"
          fit
          border
          height="500"
          highlight-current-row
          style="width: 100%;border-radius:8px;"
          :header-cell-style="{background:'#F6F5FA',color:'#4E4F62'}"
        >
          <el-table-column width="80px" type="index" label="序号" align="center" />
          <el-table-column prop="userMobile" min-width="160px" label="参与人用户名" align="center" show-overflow-tooltip />
          <el-table-column prop="userName" min-width="120px" label="昵称" align="center" show-overflow-tooltip />
          <el-table-column prop="amount" min-width="120px" label="红包金额（F）" align="center" show-overflow-tooltip />
          <el-table-column prop="receiveTime" min-width="150px" label="领取时间" align="center" show-overflow-tooltip />
        </el-table>
      </div>
    </k-dialog>
  </div>
</template>
<script>
import { getAllWebUser, getReceiveList, listRecoveryData, saveRecoveryData, updateRecoveryData, deleteRecoveryData, updateRecoveryStatus, getDescribe, setDescribe } from '@/api/red/data'
import Pagination from '@/components/Pagination'
import SearchSelect from '@/components/SearchSelect'

export default {
  components: { Pagination, SearchSelect },
  data() {
    return {
      amount: 0,
      dialogStatus: 'create',
      updateButtonState: false,
      textMap: {
        update: '修改红包',
        create: '创建红包'
      },
      totalRows: 0, // 分页组件--数据总条数
      listQuery: {
        pager: {
          pageNo: 1,
          pageSize: 10,
          totalRows: '',
          start: ''
        },
        sort: '', // 排序字段 为对应列名,
        direction: '', // 排序 正向(asc)逆向(desc),
        redPacketStatus: '',
        startTime: undefined, // 饰品外观',
        endTime: undefined, // 饰品类别',
        key: '' // 箱子名称或关键词 箱子配置界面所用'
      },
      bloodTableData: [],
      winnerUserList: [],
      userPlayList: [],
      checkedIdList: [],
      ruleGuideContent: {
        content: ''
      },
      editorOption: { //  富文本编辑器配置
        placeholder: '请输入内容',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            ['blockquote', 'code-block'], // 引用，代码块
            [{ 'header': 1 }, { 'header': 2 }], // 标题，键值对的形式；1、2表示字体大小
            [{ 'list': 'ordered' }, { 'list': 'bullet' }], // 列表
            [{ 'script': 'sub' }, { 'script': 'super' }], // 上下标
            [{ 'indent': '-1' }, { 'indent': '+1' }], // 缩进
            [{ 'direction': 'rtl' }], // 文本方向
            [{ 'size': ['small', false, 'large', 'huge'] }], // 字体大小
            [{ 'header': [1, 2, 3, 4, 5, 6, false] }], // 几级标题
            [{ 'color': [] }, { 'background': [] }], // 字体颜色，字体背景颜色
            [{ 'font': [] }], // 字体
            [{ 'align': [] }], // 对齐方式
            ['clean'], // 清除字体样式
            ['image'] // 上传图片、上传视频
          ]
        }
      },
      bloodRedInfo: {
        id: undefined,
        envelopeTheme: undefined, // 红包主题',
        envelopeIntroduce: undefined, // 红包介绍',
        receiveType: undefined, // 领取方式',
        envelopeMinAmount: undefined, // 红包最小金额',
        envelopeMaxAmount: undefined, // 红包最大金额',
        startTime: undefined, // 红包起始时间',
        endTime: undefined, // 红包结束时间',
        envelopePassword: undefined, // 红包码',
        envelopeStatus: undefined, // 红包状态',
        openStatus: undefined, // 开关',
        envelopeStatusName: undefined,
        userList: [{
          id: undefined,
          mobile: undefined
        }]
      },
      timeValue: '',
      timeCotinue: [],
      conditions: {
        keyword: null
      },
      creatRollRoom: {
        showHide: false
      },
      userListDialog: {
        showHide: false
      },
      ruleGuide: {
        showHide: false
      }
    }
  },
  watch: {
    // 时间赋值
    timeValue(val) {
      this.listQuery.startTime = this.timeValue ? this.timeValue[0] : null
      this.listQuery.endTime = this.timeValue ? this.timeValue[1] : null
    }
  },
  created() {
    this.loadData()
    this.getDescribe()
  },
  methods: {
    getSummaries(param) {
      const { columns } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) { // 第一列
          sums[index] = '总计'
        } else if (column.property === 'envelopeTheme') {
          sums[index] = this.amount
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    loadData() {
      listRecoveryData(this.listQuery).then(res => {
        this.totalRows = res.data.totalRows
        this.amount = res.data.totalData
        this.bloodTableData = res.data.rows
      })
    },
    // 肉房持续时间区间选择
    datetimerange(timeValue) {
      this.bloodRedInfo.startTime = this.timeCotinue ? timeValue[0] : null
      this.bloodRedInfo.endTime = this.timeCotinue ? timeValue[1] : null
    },
    // 请求推广用户返回列表
    requestReslutList(value) {
      getAllWebUser({ key: value }).then(res => {
        this.winnerUserList = []
        Object.assign(this.winnerUserList, res.data)
        // this.$log('checkedIdList ', this.winnerUserList)
        console.log(this.winnerUserList,'this.winnerUserList');
        this.winnerUserList = this.winnerUserList.filter(item => !this.checkedIdList.includes(item.id))
        // this.$log(this.checkedIdList, this.winnerUserList)
      })
    },
    selectChange(checkedList) {
      this.$log('checkedList', checkedList)
      this.bloodRedInfo.userList = checkedList
      this.checkedIdList = []
      this.checkedIdList = checkedList.map(item => {
        return item.id
      })
    },
    visibleChange() {
      this.winnerUserList = []
    },
    creatBloodDialog() {
      this.$resetForm(this.bloodRedInfo)
      this.timeCotinue = []
      this.winnerUserList = []
      this.dialogStatus = 'create'
      this.creatRollRoom.showHide = true
      this.updateButtonState = true
    },

    updateBloodDialog(row) {
      this.dialogStatus = 'update'
      this.updateButtonState = row.envelopeStatus === 1
      this.creatRollRoom.showHide = true
      // this.$log(row.userList)
      this.checkedIdList = []
      this.checkedIdList = row.userList.map(item => {
        return item.id
      })
      Object.assign(this.bloodRedInfo, row)
      this.winnerUserList = []
      this.timeCotinue = [row.startTime === null ? '' : row.startTime, row.endTime === null ? '' : row.endTime]
      this.$nextTick(() => {
        this.$refs.KsearchSelect.checkedList = row.userList
      })
    },
    // saveBloodRed
    saveBloodRed() {
      if (this.dialogStatus === 'create') {
        if (this.bloodRedInfo.userList === undefined || this.bloodRedInfo.userList.length <= 0) {
          this.$message.error('请至少选择一名获奖者')
          return
        }
        saveRecoveryData(this.bloodRedInfo).then(res => {
          if (res.data.success) {
            this.$message.success('保存成功')
            this.$resetForm(this.bloodRedInfo)
            this.loadData()
          } else {
            this.$message.success(res.data.msg)
          }
        })
      } else {
        updateRecoveryData(this.bloodRedInfo).then(res => {
          if (res.data.success) {
            this.$message.success('修改成功')
            this.$resetForm(this.bloodRedInfo)
            this.loadData()
          } else {
            this.$message.success(res.data.msg)
          }
        })
      }
      this.handleCloseDialog()
    },

    handleCloseDialog() {
      this.creatRollRoom.showHide = false
      this.$nextTick(() => {
        this.$refs.KsearchSelect.checkedList = []
        this.$refs.KsearchSelect.selectValueList = []
      })
    },
    deleteRedItem(id) {
      this.$confirm('确定删除么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRecoveryData({ id }).then(res => {
          if (res.data.success) {
            this.$message.success('删除成功')
            this.loadData()
          } else {
            this.$message.success(res.data.msg)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    // 保存玩法管理
    guideSave() {
      const contents = this.ruleGuideContent.content
      setDescribe({ 'key': 'envelopeRecovery', 'data': contents }).then(res => {
        this.ruleGuide.showHide = false
      })
    },
    // 加载玩法管理
    getDescribe() {
      getDescribe({ key: 'envelopeRecovery' }).then(res => {
        this.ruleGuideContent.content = res.data.msg
      })
    },

    openuserListDialog(id) {
      this.userListDialog.showHide = true
      getReceiveList({ 'envelopeId': id, 'envelopeType': 2 }).then(res => {
        this.userPlayList = res.data
      })
    },
    // roll 房状态
    updateBloodStatus(event, scope) {
      this.$log(scope.row.rollSwitch)
      updateRecoveryStatus({ 'id': scope.row.id }).then(res => {
        if (res.data.success) {
          this.$message.success('操作成功')
        } else {
          this.$message.success(res.data.msg)
        }
      })
    },
    // 搜索查询事件
    handleFilter() {
      this.listQuery.pager.pageNo = 1
      this.loadData()
    },

    ruleGuideDialog() {
      this.ruleGuide.showHide = true
    }
  }

}
</script>
<style lang="scss" scoped>
$menuText:#14162E; // 侧边栏字体颜色
$hoverColor:#1D143C;// 鼠标停留主色调浅色
$mainColor:#3b425d;// 主色调
.filter-container {
  width: 100%;
  height: 48px;
  line-height: 48px;
  .filter-item {
    display: inline-block;
    vertical-align: middle;
    margin-bottom: 10px;
  }
  .kInput{
    position:absolute;
    right: 20px;
  }
  .filter-title{
    height: 48px;
    line-height: 48px;
    font-size: 16px;
    font-weight: 500;
    margin-right: 22px;
    color: #14162E;
  }
  .user-item {
    margin-left: 10px;
    margin-right: 20px;
  }
  .room-type,.user-status,.account-status{
    margin-right: 20px;
  }
}
.red_money{
  width: 200px;
}
.grid-div{
  display: grid;
  grid-template-columns:  repeat(7, 120px);
  .item{
    height: 50px;
    font-size: 14px;
    line-height:50px;
    text-align: center;
    border: 1px solid #E3E2E7;
    width: 120px;
    overflow: hidden;
    display: inline-block;
    text-overflow: ellipsis;
    white-space: nowrap;
    padding: 0 10px;
  }
}
.top-btn{
  margin: 30px 0px 30px 0px;
  font-size: 14px;
  color: #ffffff;
   &:nth-of-type(2){
    margin-left: 10px;
  }
}
.kSelect .el-select .el-input .el-input__inner{
  width: 124px;
}

::v-deep .el-select .el-input.is-focus .el-input__inner {
    border-color: $mainColor;
}
::v-deep .el-input__inner:focus {
    border-color: $mainColor;
}
.el-form-item__label-wrap .el-form-item__label{
  float: none;
}

.dialog_creatRollRoom{
  display: flex;
  flex-direction: row;
  justify-content: center;
  margin: 40px 80px;
  ::v-deep .el-select .el-select__tags>span {
			display: none;
	}
  ::v-deep .el-range-editor.el-input__inner {
   width:400px;
}
  .el-tag + .el-tag {
    margin-left: 10px;
  }
   .el-tag {
    color: $mainColor;
    background-color: #ffffff;
    border-color: $mainColor;
    ::v-deep .el-tag__close {
      color: $mainColor;
    }
    ::v-deep .el-icon-close:hover {
      color:#ffffff;
      background: $mainColor;
    }
  }
}

.form-modify{
  display: flex;
  flex-direction: row;
  justify-content: center;
  margin: 10px 80px;
}

.editer {
  width: 500px;
  border-radius: 8px;
  float: left;
  box-sizing: border-box;
  color: #606266;
  ::v-deep .ql-container {
    height: 270px;
    border-radius: 0px 0px 8px 8px;
  }
  ::v-deep .ql-toolbar.ql-snow {
    border-radius: 8px 8px 0px 0px;
  }
}
.chargeform{
  display: flex;
  flex-direction: row;
}

::v-deep .el-switch__label.is-active {
    color: $mainColor;
}

.addBox_dialog{
  display: flex;
  flex-direction: column;
  justify-content: center;
  ::v-deep .el-dialog__body{
    width: 678px;
    margin: 40px 80px;
 }
::v-deep .el-select .el-select__tags>span {
			display: none;
	}
  .el-tag + .el-tag {
    margin-left: 10px;
  }
   .el-tag {
    color: $mainColor;
    background-color: #ffffff;
    border-color: $mainColor;
    ::v-deep .el-tag__close {
      color: $mainColor;
    }
    ::v-deep .el-icon-close:hover {
      color:#ffffff;
      background: $mainColor;
    }
  }
}
.cell-baby{
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;

}
.ellipsis-span{
  width: 80px;
  overflow: hidden;
  display: inline-block;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
